<template>
  <div class="container" v-if="isShow&&activity">
    <swiper
      :auto="false"
      style="margin:0 auto;"
      height="260px"
      :loop="true"
      ref="swiper"
      dots-position="center" v-if="activity.activityVideoId||activityMsgList.length>0">
      <swiper-item v-if="activity.activityVideoId">
        <wd-video v-if="activity.activityVideoId" style="height: 100%" @onPlayerPlay="onPlayerPlay()"
                  :src="'file/'+ activity.activityVideoId" :fileId="activity.activityVideoId"/>
      </swiper-item>
      <swiper-item v-for="(item, index) in activityMsgList" :key="index">
        <img class="swiper-img" :src="'/file/'+ item">
      </swiper-item>
    </swiper>
    <div class="section beauty">
      <div class="title">
        <span>
          <img :src="'file/'+ activity.pic" class="pic" v-if="activity.pic"/>
        </span>
        <div class="name">{{activity.beautyParlorName}}</div>
      </div>
      <div class="row">
        活动地点：{{activity.address}}
      </div>
      <div class="row">
        咨询电话：<a :href="'tel:' + activity.phone">{{activity.phone}}</a>
      </div>
      <div class="row img">
        <img :src="'/file/'+ activity.fileTitleImgId" style="width: 100%;margin-bottom: -6px">
      </div>
    </div>


    <div class="section user-info">
      <div class="section-title">
        个人信息
      </div>
      <div class="title">
        <span>
          <img :src="userInfo.headimgurl" class="pic"/>
        </span>
        <div class="name" style="white-space: nowrap;text-overflow: ellipsis;overflow-x: hidden;width: 35%;">{{userInfo.nickname}}</div>
        <div class="integrals">
          <span>当前积分:</span>
          <span class="number">{{integralsInfo.integrals}} 分</span>
        </div>
      </div>
      <div class="row">
        <div class="row time" style="color: white">
          <div class="row" v-if="activityStatus=='0'||activityStatus=='2'" style="font-size: 14px">
            活动时间：{{activity.startTime | data}} 至 {{activity.endTime | data}}
          </div>
          <div class="isSignUp" v-if="activityStatus=='1'">
            已有{{integralsInfo.num3}}人报名
          </div>
          <div class="row title" v-if="activityStatus=='0'">活动未开始</div>
          <div class="row title" v-if="activityStatus=='1'">———— 距活动结束 ————</div>
          <div class="row title" v-if="activityStatus=='2'">活动已结束</div>
          <template v-if="activityStatus=='1'">
            <template><span class="number">{{d}}</span></template>
            天
            <template><span class="number">{{h}}</span></template>
            小时
            <template><span class="number">{{m}}</span></template>
            分钟
            <template><span class="number">{{s}}</span></template>
            秒
          </template>
          <div style="height: 40px;line-height: 60px">
            <div style="position: absolute;left: 10px">
              <span>浏览次数:</span>
              <span class="num">{{integralsInfo.num1}} 次</span>
            </div>
            <div style="position: absolute;right: 10px">
              <span>分享次数:</span>
              <span class="num">{{integralsInfo.num2}} 次</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="section" v-if="singUpList.length > 0">
      <div class="section-title">
        活动参与
      </div>
      <div class="sign-up-content">
        <text-scroll :list="singUpList">
          <template slot-scope="scope">
            <div class="item">
              <span style="white-space:nowrap;text-overflow: ellipsis;overflow-x:hidden;width: 10%">{{scope.row.nickname}}</span>
              <span>{{scope.row.phone}}</span>
              <span>{{scope.row.signUpTime}}</span>
            </div>
          </template>
        </text-scroll>
      </div>
    </div>

    <div class="section" style="margin-bottom: 0" v-if="rulesImgIdList.length > 0">
      <div class="section-title">
        活动规则
      </div>
    </div>
    <div class="gift-container">
      <div class="item-gift">
        <img v-for="(item, index) in rulesImgIdList" :key="index" :src="'/file/'+ item">
      </div>
    </div>

    <div class="section" style="margin-bottom: 0" v-if="giftList.length > 0">
      <div class="section-title">
        活动礼品
      </div>
    </div>
    <div class="gift-container">
      <div class="item-gift">
        <wd-video v-if="activity.fileVideoId" :src="'file/'+ activity.fileVideoId" :fileId="activity.fileVideoId"/>
      </div>
      <div class="item-gift">
        <x-img v-for="(item, index) in giftList" :key="index" :src="'/file/'+ item"></x-img>
      </div>
    </div>


    <div class="section" style="margin-bottom: 0" v-if="statementImgIdList.length > 0">
      <div class="section-title">
        活动申明
      </div>
    </div>
    <div class="gift-container">
      <div class="item-gift">
        <x-img v-for="(item, index) in statementImgIdList" :key="index" :src="'/file/'+ item"></x-img>
      </div>
    </div>

    <div class="footer">
      <div class="btn-signup" v-if="activityStatus===0" style="background-color: #333333;color: white">
        活动未开始
      </div>
      <div class="btn-signup" @click="onConfirm1()" v-if="activityStatus===1">
        报名参与
      </div>
      <div class="btn-signup" v-if="activityStatus===2" style="background-color: #333333;color: white">
        活动已结束
      </div>
    </div>

    <confirm v-model="signupShow1"
             title="活动报名"
             hide-on-blur
             :show-cancel-button="true"
             class="signup-confirm"
             :close-on-confirm="false"
             @on-confirm="onConfirm">
      <x-input v-model="from.name" :max="10" placeholder="请输入姓名" :required="true"></x-input>
      <x-input v-model="from.phone" :max="11" placeholder="请输入手机号码" is-type="china-mobile"
               :required="true"></x-input>
    </confirm>

    <confirm v-model="signupShow2"
             title="恭喜您"
             hide-on-blur
             :show-cancel-button="false"
             class="signup-confirm"
             :close-on-confirm="false"
             @on-confirm="signupShow2 = false">
      <img class="saluteImg" :src="'/file/'+ activity.saluteImgId">
    </confirm>
    <confirm v-model="signupShow"
             title="提示"
             hide-on-blur
             :show-cancel-button="false"
             class="signup-confirm"
             :close-on-confirm="false"
             @on-confirm="signupShow = false">
      <img class="saluteImg" :src="'/file/'+ activity.repeatSaluteImgId">
    </confirm>
  </div>
  <div v-else-if="!activity" style="text-align: center;font-size: 23px;font-weight: 700;margin-top: 50%">
    该活动已下架
  </div>
</template>
<script>
  import wdVideo from "@/components/video"

  export default {
    data() {
      return {
        d: 0,
        h: 0,
        m: 0,
        s: 0,
        activityStatus: 0,
        swiperAuto: true,
        activityMsgList: [],
        rulesImgIdList: [],
        statementImgIdList: [],
        activity: {},
        endDate: new Date(),
        userInfo: {},
        integralsInfo: {},
        giftList: [],
        from: {},
        onSalutefrom: {},
        singUpList: [],
        signupShow: false,
        signupShow1: false,
        signupShow2: false,
        isShow: false,
        activityId: "",
        openId: "",
        referralsOpenId: "",
        swiperOption: {
          loop: true,
          autoplay: true,
          pagination: {
            el: '.swiper-pagination'
          }
        }
      }
    },
    components: {
      wdVideo
    },
    filters: {
      data(time) {
        if (time) {
          time = time.replace(/-/g, ':').replace(' ', ':');
          time = time.split(':');
          const d = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5]);
          const year = d.getFullYear()
          const month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : '' + (d.getMonth() + 1)
          const day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate()
          const hour = d.getHours() < 10 ? '0' + d.getHours() : '' + d.getHours()
          const minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : '' + d.getMinutes()
          const second = d.getSeconds() < 10 ? '0' + d.getSeconds() : '' + d.getSeconds()
          return year + '-' + month + '-' + day + " " + hour + ":" + minute
        }
      }
    },
    methods: {
      showSignup() {
        if (this.integralsInfo.integrals < 50) {
          this.$vux.alert.show({
            title: '提 示',
            content: "你的积分不够，快分享给微信好友为你点赞吧！"
          })
          return false;
        }
        if (this.integralsInfo.isSignUp === 0) {
          this.from = {}
          this.signupShow = true
        }
      },
      onPlayerPlay() {
        this.swiperAuto = false
      },
      onConfirm(value) {
        if (this.activityStatus == '1') {
          this.$http.post("/wx/activityInvolvement/checkSalute", {
            openId: this.openId,
            activityId: this.activityId,
          }).then(res => {
            if (this.validFrom("from")) {
              this.from.activityId = this.activityId
              this.from.openId = this.openId
              this.$http.post("/wx/activityInvolvement/signUp", this.from).then(res => {
                if (res.code === 0) {
                  this.loadAttrData()
                  this.signupShow1 = false
                  this.signupShow2 = true
                } else {
                  this.$vux.alert.show({
                    title: '提 示',
                    content: res.msg
                  })
                }
              })
            }
          })
        }
      },
      onConfirm1() {
        if (this.activityStatus == '1') {
          this.$http.post("/wx/activityInvolvement/checkSalute", {
            openId: this.openId,
            activityId: this.activityId,
          }).then(res => {
            if (res.code === 1) {
              this.signupShow = true
            } else {
              this.onSalutefrom = {}
              this.signupShow1 = true
            }
          })
        }
      },
      onSalute() {
        if (this.activityStatus == '1') {
          if (this.validFrom("onSalutefrom")) {
            this.$http.post("/wx/activityInvolvement/salute", {
              openId: this.openId,
              activityId: this.activityId,
              referralsOpenId: this.referralsOpenId,
              username: this.onSalutefrom.name,
              phone: this.onSalutefrom.phone
            }).then(res => {
              if (res.code === 0) {
                this.loadAttrData()
                this.signupShow1 = false
                this.signupShow2 = true
              } else {
                this.$vux.alert.show({
                  title: '提 示',
                  content: res.msg
                })
              }
            })
          }
        }
      },
      loadData(id, openId) {
        this.loadAttrData()
        this.$http.get(`/wx/activity/${id}/${openId}?referralsOpenId=` + this.referralsOpenId).then(res => {
          if (res.code === 0) {
            const {activity, userInfo, attr} = res.data;
            this.activity = activity;
            this.userInfo = userInfo;
            this.attr = attr;
            if (activity != null) {
              if (activity.activityImgId != null && activity.activityImgId != '') {
                this.activityMsgList = activity.activityImgId.split(",");
              }
              if (activity.rulesImgId != null) {
                this.rulesImgIdList = activity.rulesImgId.split(",");
              }
              if (activity.statementImgId != null && activity.statementImgId != '') {
                this.statementImgIdList = activity.statementImgId.split(",");
              }
              if (activity.fileImgId != null && activity.fileImgId != '') {
                this.giftList = activity.fileImgId.split(",");
              }

              this.loadSingUpList()
              this.wxConfig()
              window.document.title = activity.name
              this.countTime()
              setTimeout(function () {
                var video = document.getElementById("vjs_video_3")
                if (video) {
                  video.children[4].click()
                }
              }, 1000)
            }
            this.isShow = true;
          }
        })
      },
      loadAttrData() {
        this.$http.get('/wx/activity/integralsInfo/' + this.activityId + '/' + this.openId + '?referralsOpenId=' + this.referralsOpenId).then(res => {
          if (res.code === 0) {
            this.integralsInfo = res.data;
          }
        })
      },
      getQueryString(name) {
        const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        const r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      },

      loadSingUpList() {
        this.$http.get("/wx/activityInvolvement/singUpList/" + this.activityId).then(res => {
          if (res.code === 0) {
            this.singUpList = res.data
          }
        })
      },

      /*********** 微信 ***********/
      wxConfig() {
        this.$http.post("/wechat/getSignature", {webUrl: location.href.split('#')[0]}).then(res => {
          this.initWxData(res.data)
        })
      },
      initWxData(config) {
        wx.config({
          debug: false,
          appId: config.appId,
          timestamp: config.timestamp,
          nonceStr: config.nonceStr,
          signature: config.signature,
          jsApiList: [
            'onMenuShareTimeline',
            'onMenuShareAppMessage'
          ]
        })
        this.share()
      },
      validFrom(val) {
        var test = /^[0-9]{11}$/
        if (val == 'from') {
          if (!this.from.name) {
            this.$vux.alert.show({
              title: '提 示',
              content: "姓名必填！"
            })
            return false;
          }
          if (!this.from.phone || !test.test(this.from.phone)) {
            this.$vux.alert.show({
              title: '提 示',
              content: "手机号有误！"
            })
            return false;
          }
        } else {
          if (!this.onSalutefrom.name) {
            this.$vux.alert.show({
              title: '提 示',
              content: "姓名必填！"
            })
            return false;
          }
          if (!this.onSalutefrom.phone || !test.test(this.onSalutefrom.phone)) {
            this.$vux.alert.show({
              title: '提 示',
              content: "手机号有误！"
            })
            return false;
          }
        }
        return true;
      },
      validOpenId() {
        const activityId = this.getQueryString("id");
        if (!activityId) {
          this.$vux.alert.show({
            title: '错 误',
            content: "参数缺失。"
          })
          return
        }
        if (activityId == 'null') {
          this.$vux.alert.show({
            title: '错 误',
            content: "请先创建活动。"
          })
          return
        }
        this.activityId = activityId;
        let openId = null
        // let openId = localStorage.getItem("openid")
        // let openId = "okJFbwgdI6e1ekJ3NCBaHHdR1o1I"
        if (!openId) {
          openId = this.getQueryString("openid");
          if (openId) {
            localStorage.setItem("openid", openId);
          } else {
            location.href = location.origin + "/wechat/authorize?returnUrl=" + location.href
            return
          }
        }
        this.openId = openId;
        this.referralsOpenId = this.getQueryString("referralsOpenId") || null;
        this.loadData(activityId, openId)

      },
      share() {
        var _this = this
        let url = location.origin + "/activityShare.html?id=" + this.activityId + "&referralsOpenId=" + this.openId
        const shareOption = {
          title: this.activity.shareTitle,
          desc: this.activity.shareContent, // 分享描述
          link: url, // 分享链接
          imgUrl: location.origin + '/file/' + this.activity.pic, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
            _this.$http.post("/wx/activityInvolvement/activityShare", {openId: _this.openId,activityId:_this.activityId,referralsOpenId:_this.referralsOpenId}).then(res => {
              console.log("分享成功！！")
              _this.loadAttrData()
            })
          }
        }
        wx.ready(function () {
          wx.onMenuShareAppMessage(shareOption)
          wx.onMenuShareTimeline(shareOption)
          wx.error(function (res) {
            console.log(res.errMsg)
          })
        });
      },
      isWxPlatform() {
        return /MicroMessenger|wechatdevtools/ig.test(window.navigator.userAgent)
      },
      countTime() {
        var date = null;
        var endDate = null
        var start = this.activity.startTime.replace(new RegExp('-', "g"), "/");
        var end = this.activity.endTime.replace(new RegExp('-', "g"), "/");
        if (new Date() > new Date(end)) {
          this.activityStatus = 2
          endDate = new Date();
          date = new Date();
        } else if (new Date() > new Date(start)) {
          this.activityStatus = 1
          endDate = new Date(end);
          date = new Date();
        } else if (new Date() < new Date(start)) {
          this.activityStatus = 0
          endDate = new Date(start);
          date = new Date();
        }
        //获取当前时间
        var now = date.getTime();
        //设置截止时间
        var end = endDate.getTime();
        //时间差
        var leftTime = end - now;
        if (leftTime > 0) {
          //定义变量 d,h,m,s保存倒计时的时间
          var day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
          var hours = Math.floor(leftTime / 1000 / 60 / 60 % 24);
          var minute = Math.floor(leftTime / 1000 / 60 % 60);
          var secnnd = Math.floor(leftTime / 1000 % 60);
          this.d = day < 10 ? "0" + day : day
          this.h = hours < 10 ? "0" + hours : hours
          this.m = minute < 10 ? "0" + minute : minute
          this.s = secnnd < 10 ? "0" + secnnd : secnnd
          //递归每秒调用countTime方法，显示动态时间效果
          setTimeout(this.countTime, 1000);
        }
      }
    },
    created() {
      /*if(!this.isWxPlatform()){
        location.href=location.origin + "/wechat/authorize?returnUrl="+location.href
        return
      }*/
      this.validOpenId()
//      this.$wechat.ready(() => this.share())
    }
  }
</script>

<style lang="sass" scoped>
  .container
    background-color: #f2f2f2
    height: 100%
    margin-bottom: 50px

    .section
      padding: 10px
      margin: 10px 0
      background-color: #ffffff
      color: #333333

      .section-title
        padding: 0 10px
        border-left: 2px solid
        margin-bottom: 10px
        color: #ffc600
        font-weight: 600

      &.beauty
        margin-top: 0
        .img
          margin: 10px -10px -10px -10px

    .title
      position: relative

      .pic
        width: 50px
        height: 50px
        border-radius: 100%

      .name
        position: absolute
        top: 0
        margin-left: 60px
        line-height: 50px

      .integrals
        position: absolute
        top: 0
        right: 0
        line-height: 45px

    .user-info
      color: black

      .time
        background-color: #4F4E4E
        color: black
        font-weight: 700
        text-align: center
        margin: 10px -10px -10px -10px
        padding: 15px 0px

        .isSignUp
          font-size: 20px
          font-weight: 700
          background-color: #ffc600
          padding: 5px
          width: 50%
          margin: 10px auto
          border-radius: 5px
          color: black
        .title
          margin: 15px 0 0 0

      .number
        margin-left: 5px
        font-weight: 700
        color: #ffc600
        font-size: 23px
      .num
        color: #ffc600
        font-size: 18px

      .praise
        display: flex
        justify-content: space-between

    .activity-content
      padding: 5px 10px
      border: 1px dotted #bbbbbb
      border-radius: 8px

      p
        margin: 0
        padding: 5px 8px
        line-height: 1.5

    .gift-container
      margin-bottom: 10px
      line-height: 0

      img
        width: 100%

    .sign-up-content
      padding: 5px 10px
      border: 1px dotted #bbbbbb
      border-radius: 8px

      p
        font-size: 12px
        line-height: 30px

    .overview-content
      p
        text-indent: 2em
        line-height: 1.5
        color: #333333

    .row
      line-height: 1.5

    .icon-praise
      color: #ffc600
      margin-left: 10px

    .footer
      position: fixed
      bottom: 0
      width: 100%
      height: 50px
      background: #ffffff
      display: flex

      > div
        flex-grow: 1
        text-align: center
        line-height: 50px

      .btn-signup
        background-color: #ffc600
        font-size: 18px
        font-weight: 700

        &.btn-disabled
          background-color: #eeeeee
          color: #333333

    .swiper-img
      width: 100%
      height: 300px

    .item
      font-size: 14px
      padding: 3px
      display: flex
      justify-content: space-between

    .item-gift
      width: 100%

    .saluteImg
      width: 100%
</style>
<style lang="sass">
  .signup-confirm .weui-dialog__btn_primary
    color: black
</style>
<style>
  .weui-dialog__bd{
    padding: 0px !important
  }

  .vjs_video_3-dimensions {
    height: 100% !important;
  }

  .vjs-custom-skin > .video-js .vjs-big-play-button {
    font-size: 2rem !important;
    height: 2.5rem !important;
    width: 2.5rem !important;
    -webkit-border-radius: 50% !important;
    -moz-border-radius: 50% !important;
    border-radius: 50% !important;
    left: 57% !important;
    top: 57% !important;
    line-height: 1.2em !important;
  }

  .vjs-poster {
    height: 260px !important;
  }

  .vjs-tech {
    height: 260px !important;
  }

  .video-js {
    height: 260px !important;
  }
</style>
